package com.example.badminton.controller;

import com.example.badminton.common.AnonymousAccess;
import com.example.badminton.common.Result;
import com.example.badminton.entity.User;
import com.example.badminton.service.UserService;
import com.example.badminton.utils.JwtUtils;
import com.example.badminton.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @AnonymousAccess
    @PostMapping("/register")
    public Result<User> register(@RequestBody User user) {
        // 检查用户名是否已存在
        if (userService.isUsernameExists(user.getUsername())) {
            return Result.error("用户名已存在");
        }
        
        // 设置默认角色
        user.setRole("user");
        userService.save(user);
        
        // 不返回密码
        user.setPassword(null);
        return Result.success(user);
    }

    @AnonymousAccess
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody User loginUser) {
        User user = userService.login(loginUser.getUsername(), loginUser.getPassword());
        if (user == null) {
            return Result.error("用户名或密码错误");
        }
        
        // 生成token
        String token = JwtUtils.generateToken(user.getId());
        
        // 构建返回数据
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", user);
        
        return Result.success(result);
    }

    @GetMapping("/profile")
    public Result<User> getProfile() {
        User user = UserUtils.getCurrentUser();
        user.setPassword(null);
        return Result.success(user);
    }

    @PutMapping("/profile")
    public Result<User> updateProfile(@RequestBody User user) {
        Long userId = UserUtils.getCurrentUserId();
        user.setId(userId);
        userService.updateById(user);
        
        // 不返回密码
        user.setPassword(null);
        return Result.success(user);
    }

    @PostMapping("/change-password")
    public Result<String> changePassword(@RequestBody Map<String, String> passwordData) {
        Long userId = UserUtils.getCurrentUserId();
        String oldPassword = passwordData.get("oldPassword");
        String newPassword = passwordData.get("newPassword");
        
        if (oldPassword == null || newPassword == null) {
            return Result.error("密码不能为空");
        }
        
        boolean success = userService.changePassword(userId, oldPassword, newPassword);
        if (success) {
            return Result.success("密码修改成功");
        } else {
            return Result.error("原密码错误");
        }
    }

    @GetMapping("/list")
    public Result<java.util.List<User>> getUserList() {
        // 检查管理员权限
        if (!UserUtils.isAdmin()) {
            return Result.error("无权限查看用户列表");
        }
        
        java.util.List<User> users = userService.list();
        // 不返回密码
        users.forEach(user -> user.setPassword(null));
        return Result.success(users);
    }

    @DeleteMapping("/{id}")
    public Result<String> deleteUser(@PathVariable Long id) {
        // 检查管理员权限
        if (!UserUtils.isAdmin()) {
            return Result.error("无权限删除用户");
        }
        
        userService.removeById(id);
        return Result.success("删除成功");
    }
} 